package com.lark.component;

import com.alibaba.fastjson2.JSONObject;
import com.lark.constant.FileConstant;
import com.lark.context.ApplicationContext;
import com.lark.utils.FileUtil;
import com.lark.utils.ImageUtil;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.media.MediaPlayer;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Timer;
import java.util.TimerTask;

import static com.lark.context.ApplicationContext.clientModel;
import static com.lark.context.ApplicationContext.stage;

/**
 * @Description: 系统托盘组件
 * @Version: 1.0
 */
@Slf4j
public class TrayComponent extends Component {

    private static TrayComponent instance;
    // 正在闪烁
    private boolean isFlicker = false;
    // 正在播放声音
    private boolean isSound = false;
    // 托盘图标
    TrayIcon trayIcon;
    Timer timer;
    TimerTask task;
    MediaPlayer mediaPlayer;
    String mp3Path;
    BufferedImage showImage;
    BufferedImage hideImage;

    private TrayComponent() {
        showImage = SwingFXUtils.fromFXImage(ImageUtil.getIcon("tray_show.png"), null);
        mp3Path = TrayComponent.class.getResource("/static/sounds/alert.mp3").toExternalForm();
        hideImage = SwingFXUtils.fromFXImage(ImageUtil.getIcon("tray_hide.png"), null);
        initComponent();
    }

    public static TrayComponent getInstance() {
        if (instance == null) {
            instance = new TrayComponent();
        }
        return instance;
    }

    @Override
    public void initComponent() {
        // 拒绝隐式退出
        Platform.setImplicitExit(false);
        // 获取系统托盘
        SystemTray systemTray = SystemTray.getSystemTray();

        // 创建右键菜单
        PopupMenu popup = new PopupMenu();
        MenuItem settingItem = new MenuItem("设置");
        settingItem.addActionListener(e -> System.out.println("后续在做"));
        popup.add(settingItem);
        MenuItem exitItem = new MenuItem("退出");
        exitItem.addActionListener(e -> {
            // 更新配置到文件中
            Path filePath = Paths.get(FileConstant.DEFAULT_CONF_PATH, clientModel.defaultConfPath(), clientModel.defaultConfFile());
            FileUtil.save(filePath.toString(), JSONObject.toJSONString(ApplicationContext.settingModel));
            System.exit(1);
        });
        popup.add(exitItem);
        // TODO 继续增加菜单

        // 创建托盘图标 - Windows的托盘图标最好是16*16的PNG图像
        trayIcon = new TrayIcon(showImage, clientModel.client(), popup);
        trayIcon.setImageAutoSize(true);
        // 添加事件监听 - 双击图标恢复窗口
        trayIcon.addActionListener(e -> restoreWindow());

        try {
            systemTray.add(trayIcon);
        } catch (AWTException e) {
            log.error("System tray loading failed", e);
        }

        // 隐藏窗口事件
        stage.setOnHidden(event -> {
            if (stage.isIconified()) {
                // 取消最小化 - 先最小化在关闭窗口，则恢复窗口时仍然是最小化状态，所以需要取消最小化
                stage.setIconified(false);
            }
            if (stage.isShowing()) {
                stage.hide();
            }
            event.consume();
        });
    }

    /**
     * 恢复窗口
     */
    private void restoreWindow() {
        Platform.runLater(() -> {
            if (!stage.isShowing()) {
                stage.show();
            }
            stage.toFront();
        });
    }
}
